package com.tech.zhidengxian.service.impl;

import com.tech.zhidengxian.mapper.ReceiverAddressMapper;
import com.tech.zhidengxian.model.dataobject.ReceiverAddressDO;
import com.tech.zhidengxian.model.dto.ReceiverAddressDTO;
import com.tech.zhidengxian.service.api.ReceiverAddressService;
import com.tech.zhidengxian.util.JacksonUtils;
import com.tech.zhidengxian.util.ResultAssert;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ReceiverAddressServiceImpl implements ReceiverAddressService {
    @Resource
    private ReceiverAddressMapper addressMapper;
    @Override
    public List<ReceiverAddressDTO> queryAddressListByUid(Long uid) {
        List<ReceiverAddressDO> addressDOList = addressMapper.queryAddressListByUid(uid);
        return JacksonUtils.convertList(addressDOList, ReceiverAddressDTO.class);
    }

    @Override
    public ReceiverAddressDTO updateById(ReceiverAddressDTO receiverAddressDTO) {
        ReceiverAddressDO addressDO = JacksonUtils.convert(receiverAddressDTO, ReceiverAddressDO.class);
        int update = addressMapper.updateById(addressDO);
        ResultAssert.assertGreaterThanZero(update,"地址更新异常");
        return receiverAddressDTO;
    }

    @Override
    public ReceiverAddressDTO insert(ReceiverAddressDTO receiverAddressDTO) {
        ReceiverAddressDO addressDO = JacksonUtils.convert(receiverAddressDTO, ReceiverAddressDO.class);
        int insert = addressMapper.insert(addressDO);
        ResultAssert.assertGreaterThanZero(insert,"地址更新异常");
        return JacksonUtils.convert(addressDO,ReceiverAddressDTO.class);
    }

    @Override
    public ReceiverAddressDTO queryUserDefAddress(Long uid) {
        List<ReceiverAddressDTO> addressDTOS = queryAddressListByUid(uid);
        ReceiverAddressDTO addressDTO = null;
        if (addressDTOS.size() > 0) {
            ReceiverAddressDTO dto = addressDTOS.stream().filter(ReceiverAddressDTO::getIsDefault).findAny().orElse(null);
            addressDTO = dto == null ? addressDTOS.get(0) : dto;
        }
        return addressDTO;
    }
}
